package com.lagou.utils;

/**
 * @Author ZHAO Yudong
 * @Date 2020/11/6 14:26
 * @description：
 */

import com.lagou.annotion.MyAutowired;
import com.lagou.annotion.MyService;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author lijun
 * <p>
 * 事务管理器类：负责手动事务的开启、提交、回滚
 */
@Slf4j
@MyService
public class TransactionManager {

    @MyAutowired
    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /*private TransactionManager(){

    }

    private static TransactionManager transactionManager = new TransactionManager();

    public static TransactionManager getInstance() {
        return  transactionManager;
    }*/

    public void beginTransaction() throws SQLException {
        connectionUtils.getCurrentThreadConn().setAutoCommit(false);
    }


    // 提交事务
    public void commit() throws SQLException {
        connectionUtils.getCurrentThreadConn().commit();
    }


    // 回滚事务
    public void rollback() throws SQLException {
        connectionUtils.getCurrentThreadConn().rollback();
    }

    // 释放连接资源
    public void release() throws Exception{
        Connection conn = connectionUtils.getCurrentThreadConn();
        conn.close();
        connectionUtils.release();//从当前线程上移除Connection对象
    }

}
